package com.oedtech.esl.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * http请求工具
 */
public class HttpUtils {
    public final static Logger LOGGER= LoggerFactory.getLogger(HttpUtils.class);

    public static String sendPost(String urlString ,String param) {
        JSONObject returnJson = null;
        String result="";
        try {
            // 创建连接
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");//**注意点1**，需要此格式，后边这个字符集可以不设置
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());
            out.write(param.getBytes("UTF-8"));//**注意点2**，需要此格式
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));//**注意点3**，需要此格式
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
//            System.out.println("sb:"+sb);
//            returnJson = JSONObject.fromObject(sb.toString());
            result=sb.toString();
            reader.close();
            // 断开连接
            connection.disconnect();
        }catch (MalformedURLException e){
            LOGGER.warn(e.getMessage());
        }
        catch (ConnectException e){
            LOGGER.warn(e.getMessage());
        } catch (IOException e) {
            LOGGER.error("",e);
        }
        return result;
    }

}
